package com.travel.modules.alipay.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.travel.commons.annotation.SysLog;
import com.travel.commons.shiro.ShiroUserGetter;
import com.travel.commons.utils.*;
import com.travel.commons.validator.ValidatorUtils;
import com.travel.commons.validator.groups.AddGroup;
import com.travel.commons.validator.groups.UpdateGroup;
import com.travel.modules.alipay.entity.OrderForm;
import com.travel.modules.alipay.service.OrderFormService;
import com.travel.modules.asset.entity.Goods;
import com.travel.modules.asset.entity.Hotel;
import com.travel.modules.asset.entity.Route;
import com.travel.modules.asset.service.GoodsService;
import com.travel.modules.sys.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrderFormController {
    @Resource
    private OrderFormService orderFormService;

    @Resource
    private GoodsService goodsService;

    @Resource
    private SysConfigService sysConfigService;

    private static final String SYSTEM_CONFIG_ORDER_EXPIRE = "SYSTEM_CONFIG_ORDER_EXPIRE";

    @RequestMapping("/list")
    public R list(@RequestBody Map<String, Object> param) {
        Integer page = (Integer) param.get("page");
        Integer limit = (Integer) param.get("limit");
        if (page == null || limit == null) {
            return R.error("缺少分页参数");
        }
        QueryWrapper<OrderForm> queryWrapper = new QueryWrapper<>();
        if (!ObjectUtils.isEmpty(param.get("goodsId"))) {
            queryWrapper.eq("goodsId", param.get("goodsId"));
        }
        List<OrderForm> list = orderFormService.list(queryWrapper);
        return R.ok().put("page", PageUtils.getPage(list, limit, page));
    }

    @RequestMapping("/list/current")
    public R list2Current(@RequestBody Map<String, Object> param) {
        Integer type = (Integer) param.get("type");
        if (type == null || (type != 1 && type != 2)) {
            return R.ok().put("page", new ArrayList<>());
        }
        param.put("currentUserId", ShiroUserGetter.getUserId());
        return R.ok().put("page", orderFormService.getAllOrder23(param));
    }

    @RequestMapping("/list/merchant")
    public R list2Merchant(@RequestBody Map<String, Object> param) {
        Integer page = (Integer) param.get("page");
        Integer limit = (Integer) param.get("limit");
        if (page == null || limit == null) {
            return R.error("缺少分页参数");
        }
        Integer type = (Integer) param.get("type");
        if (type == null || (type != 1 && type != 2)) {
            return R.ok().put("page", new ArrayList<>());
        }
        param.put("merchantId", ShiroUserGetter.getUserId());
        return R.ok().put("page", PageUtils.getPage(orderFormService.getAllOrder2Merchant(param), limit, page));
    }

    @RequestMapping("/list/merchant/completed")
    public R list2MerchantComplete(@RequestBody Map<String, Object> param) {
        Integer page = (Integer) param.get("page");
        Integer limit = (Integer) param.get("limit");
        if (page == null || limit == null) {
            return R.error("缺少分页参数");
        }
        Integer type = (Integer) param.get("type");
        if (type == null || (type != 1 && type != 2)) {
            return R.ok().put("page", new ArrayList<>());
        }
        param.put("merchantId", ShiroUserGetter.getUserId());
        return R.ok().put("page", PageUtils.getPage(orderFormService.getCompletedOrder2Merchant(param), limit, page));
    }

    @RequestMapping("/list/merchant/uncompleted")
    public R list2MerchantUncompleted(@RequestBody Map<String, Object> param) {
        Integer page = (Integer) param.get("page");
        Integer limit = (Integer) param.get("limit");
        if (page == null || limit == null) {
            return R.error("缺少分页参数");
        }
        Integer type = (Integer) param.get("type");
        if (type == null || (type != 1 && type != 2)) {
            return R.ok().put("page", new ArrayList<>());
        }
        param.put("merchantId", ShiroUserGetter.getUserId());
        return R.ok().put("page", PageUtils.getPage(orderFormService.getUncompletedOrder2Merchant(param), limit, page));
    }

    /**
     * 创建订单
     * @param form 订单信息
     */
    @RequestMapping("/create")
    public R create(@RequestBody OrderForm form) {
        ValidatorUtils.validate(form, AddGroup.class);
        String goodsId = form.getGoodsId();
        BigDecimal pay;
        if (goodsId.contains("r-")) {
            form.setType(1);
            Route route = (Route) goodsService.getGoodsObject(goodsId);
            pay = route.getAdPrice().multiply(new BigDecimal(form.getAdNum() == null ? 0 : form.getAdNum()))
                    .add(route.getChPrice().multiply(new BigDecimal(form.getChNum() == null ? 0 : form.getChNum())));
        } else if (goodsId.contains("h-")) {
            form.setType(2);
            Hotel hotel = (Hotel) goodsService.getGoodsObject(goodsId);
            pay = hotel.getEconomyPrice().multiply(new BigDecimal(form.getEconomyNum() == null ? 0 : form.getEconomyNum()))
                    .add(hotel.getSinglePrice().multiply(new BigDecimal(form.getSingleNum() == null ? 0 : form.getSingleNum())))
                    .add(hotel.getDoublePrice().multiply(new BigDecimal(form.getDoubleNum() == null ? 0 : form.getDoubleNum())))
                    .add(hotel.getManyPrice().multiply(new BigDecimal(form.getManyNum() == null ? 0 : form.getManyNum())))
                    .add(hotel.getVipPrice().multiply(new BigDecimal(form.getVipNum() == null ? 0 : form.getVipNum())));
        } else {
            return R.error("商品错误");
        }
        form.setPay(pay);
        int expire = Integer.parseInt(sysConfigService.getValue(SYSTEM_CONFIG_ORDER_EXPIRE));
        form.setUserId(ShiroUserGetter.getUserId());
        form.setOrderId(new SnowNoGenerator().generate());
        form.setExpireTime(DateUtils.addDateMinutes(new Date(), expire));
        /* 默认未付款 */
        form.setStatus(0);
        orderFormService.save(form);
        return R.ok().put("page", form);
    }

    /**
     * 查询订单信息
     * @param form orderId - 订单号
     * @return 订单信息
     */
    @RequestMapping("/info")
    public R info(@RequestBody OrderForm form) {
        ValidatorUtils.validate(form, UpdateGroup.class);
        OrderForm orderForm = orderFormService.getOne(new QueryWrapper<OrderForm>().eq("order_id", form.getOrderId()));
        if (orderForm == null) {
            return R.error("订单查询失败");
        }
        String goodsId = orderForm.getGoodsId();
        /* 查询商品信息 */
        Object goodsObj = goodsService.getGoodsObject(goodsId);
        if (goodsObj == null) {
            return R.error("商品不存在");
        }
        return R.ok().put("page", orderForm)
                     .put("goods", goodsObj);
    }

    /**
     * 订单修改
     * @param form 修改信息
     */
    @RequestMapping("/edit")
    public R edit(@RequestBody OrderForm form) {
        ValidatorUtils.validate(form, UpdateGroup.class);
        OrderForm old = orderFormService.getOne(new QueryWrapper<OrderForm>().eq("order_id", form.getOrderId()));
        if (old == null) {
            return R.error("订单不存在");
        }
        /* 不能修改商品、用户id、状态 */
        form.setGoodsId(null);
        form.setUserId(null);
        form.setStatus(null);
        BeanUtils.copyProperties(form, old);
        String goodsId = old.getGoodsId();
        BigDecimal pay;
        if (old.getType() == 1) {// 线路订单
            Route route = (Route) goodsService.getGoodsObject(goodsId);
            pay = route.getAdPrice().multiply(new BigDecimal(form.getAdNum() == null ? 0 : form.getAdNum()))
                    .add(route.getChPrice().multiply(new BigDecimal(form.getChNum() == null ? 0 : form.getChNum())));
        } else if(old.getType() == 2) {// 酒店订单
            Hotel hotel = (Hotel) goodsService.getGoodsObject(goodsId);
            pay = hotel.getEconomyPrice().multiply(new BigDecimal(form.getEconomyNum() == null ? 0 : form.getEconomyNum()))
                    .add(hotel.getSinglePrice().multiply(new BigDecimal(form.getSingleNum() == null ? 0 : form.getSingleNum())))
                    .add(hotel.getDoublePrice().multiply(new BigDecimal(form.getDoubleNum() == null ? 0 : form.getDoubleNum())))
                    .add(hotel.getManyPrice().multiply(new BigDecimal(form.getManyNum() == null ? 0 : form.getManyNum())))
                    .add(hotel.getVipPrice().multiply(new BigDecimal(form.getVipNum() == null ? 0 : form.getVipNum())));
        } else {
            return R.error("商品错误");
        }
        old.setPay(pay);
        orderFormService.updateById(old);
        return R.ok();
    }

    @RequestMapping("/status")
    public R status(@RequestBody OrderForm form) {
        String orderId = form.getOrderId();
        if (orderId == null) {
            return R.error("缺少订单号");
        }
        if (form.getStatus() == null) {
            return R.error("缺少状态参数");
        }
        OrderForm orderForm = orderFormService.getOne(new QueryWrapper<OrderForm>().eq("order_id", orderId));
        orderForm.setStatus(form.getStatus());
        orderFormService.updateById(orderForm);
        log.warn("用户 : {}, 订单状态更新至{}, 订单号 : {}", orderForm.getUserId(), orderForm.getStatus(), orderForm.getOrderId());
        return R.ok();
    }

    /**
     * 用户取消订单
     * @param form orderId - 订单号
     */
    @RequestMapping("/cancel")
    public R cancel(@RequestBody OrderForm form) {
        String orderId = form.getOrderId();
        if (orderId == null) {
            return R.error("缺少订单号");
        }
        OrderForm editor = new OrderForm();
        editor.setOrderId(orderId);
        editor.setStatus(-1);
        OrderForm old = orderFormService.getOne(new QueryWrapper<OrderForm>().eq("order_id", orderId));
        BeanUtils.copyProperties(editor, old);
        orderFormService.updateById(old);
        return R.ok();
    }

    /**
     * 删除订单
     * @param form 订单号
     */
    @SysLog("订单删除")
    @RequestMapping("/del")
    public R del(@RequestBody OrderForm form) {
        ValidatorUtils.validate(form, UpdateGroup.class);
        return orderFormService.remove(new QueryWrapper<OrderForm>().eq("order_id", form.getOrderId())) ? R.ok() : R.error("无该订单");
    }
}
